package com.leetcode.剑指offer专项突击版;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 覃国强
 * @date 2022-02-28 16:07
 */
public class 剑指OfferII_005_单词长度的最大乘积 {


  static
  class Solution {
    public int maxProduct(String[] words) {
      if (words == null || words.length < 2) {
        return 0;
      }

      Map<Integer, Integer> bitMaskMap = new HashMap<>();
      for (String word : words) {
        int bitMask = generateBitMask(word);
        bitMaskMap.compute(bitMask, (key, oldValue) -> oldValue == null ? word.length() : Math.max(oldValue, word.length()));
      }

      int answer = 0;
      for (Map.Entry<Integer, Integer> x : bitMaskMap.entrySet()) {
        for (Map.Entry<Integer, Integer> y : bitMaskMap.entrySet()) {
          if ((x.getKey() & y.getKey()) == 0) {
            answer = Math.max(answer, x.getValue() * y.getValue());
          }
        }
      }
      return answer;
    }

    private int generateBitMask(String word) {
      int bitMask = 0;
      for (char ch : word.toCharArray()) {
        bitMask |= (1 << (ch - 'a'));
      }
      return bitMask;
    }
  }

}
